﻿using System;
using Abp.Configuration.Startup;
using Abp.Domain.Uow;
using AbpBuild;
using AbpBuild.Configuration;
using AbpBuild.EntityFrameworkCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;


namespace AbpBuild.EntityFrameworkCore
{
    public class MyConnectionStringResolver : DefaultConnectionStringResolver
    {
        private readonly IConfigurationRoot _appConfiguration;
        readonly ICurrentUnitOfWorkProvider _currentUnitOfWorkProvider;
        public MyConnectionStringResolver(ICurrentUnitOfWorkProvider currentUnitOfWorkProvider, IAbpStartupConfiguration configuration,IHostingEnvironment hostingEnvironment) 
            : base(configuration)
        {
            _appConfiguration =
                AppConfigurations.Get(hostingEnvironment.ContentRootPath, hostingEnvironment.EnvironmentName);
            _currentUnitOfWorkProvider = currentUnitOfWorkProvider;
        }

        public override string GetNameOrConnectionString(ConnectionStringResolveArgs args)
        {
            if (args["DbContextConcreteType"] as Type == typeof(AbpBuildWenShuDbContext))
            {
                int? a = GetCurrentTenantId();
                if (a == null)
                {
                    return _appConfiguration.GetConnectionString(AbpBuildConsts.WenShuDbConnectionStringName);
                }
                else
                {
                    return _appConfiguration.GetConnectionString(a.ToString());
                }
            }
            if (args["DbContextConcreteType"] as Type == typeof(AbpBuildDbContext))
            {
                return _appConfiguration.GetConnectionString(AbpBuildConsts.ConnectionStringName);
            }
            return base.GetNameOrConnectionString(args);
        }

        protected virtual int? GetCurrentTenantId()
        {
            return _currentUnitOfWorkProvider.Current != null
                ? _currentUnitOfWorkProvider.Current.GetTenantId()
                : null;
        }

    }
}